package main

import (
	"fmt"

	"github.com/jinzhu/gorm"
	"github.com/micro/go-micro/v2"
	log "github.com/micro/go-micro/v2/logger"
	"github.com/micro/go-micro/v2/registry"
	consul "github.com/micro/go-plugins/registry/consul/v2"
	limiter "github.com/micro/go-plugins/wrapper/ratelimiter/uber/v2"
	tracing "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
	"github.com/opentracing/opentracing-go"

	"gitee.com/waagik/demo/common"
	"gitee.com/waagik/demo/domain/model"
	"gitee.com/waagik/demo/handler"
	"gitee.com/waagik/demo/proto/demo"
	"gitee.com/waagik/demo/proto/greeter"
	"gitee.com/waagik/demo/subscriber"
)

var QPS = 100

func main() {
	serviceName := "go.micro.service.demo"
	//go greeterSvc()

	//配置中心
	consulConfig, err := common.GetConsulConfig("127.0.0.1", 8500, "/micro/config")
	if err != nil {
		log.Error(err)
	}

	//注册中心
	consulRegistry := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{
			"127.0.0.1:8500",
		}
	})

	//链路追踪
	t, io, err := common.NewTracer(serviceName, "localhost:6831")
	if err != nil {
		log.Error(err)
	}
	defer io.Close()
	opentracing.SetGlobalTracer(t)

	// New Service
	service := micro.NewService(
		micro.Name(serviceName),
		micro.Version("latest"),

		//这里设置地址和需要暴露的端口
		micro.Address("0.0.0.0:8086"),
		//添加consul 作为注册中心
		micro.Registry(consulRegistry),

		//链路追踪
		micro.WrapHandler(tracing.NewHandlerWrapper(opentracing.GlobalTracer())),
		//添加限流
		micro.WrapHandler(limiter.NewHandlerWrapper(QPS)),
	)

	//获取mysql配置,路径中不带前缀
	mysqlInfo := common.GetMysqlFromConsul(consulConfig, "mysql")

	//连接数据库
	db, err := gorm.Open("mysql", mysqlInfo.User+":"+mysqlInfo.Pwd+"@/"+mysqlInfo.Database+"?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		log.Error(err)
	}
	defer db.Close()

	//禁止复表
	db.SingularTable(true)

	model.SetDb(db)

	// Initialise service
	service.Init()

	//
	// Register Handler
	demo.RegisterDemoHandler(service.Server(), new(handler.Demo))

	// Register Struct as Subscriber
	micro.RegisterSubscriber("go.micro.service.demo", service.Server(), new(subscriber.Demo))

	// Run service
	if err := service.Run(); err != nil {
		log.Fatal(err)
	}

}

func greeterSvc() {
	fmt.Println("greeterSvc...")
	// New Service
	greeterSvc := micro.NewService(
		micro.Name("go.micro.service.greeter"),
		micro.Version("latest"),
	)

	// Initialise service
	greeterSvc.Init()

	// Register Handler
	greeter.RegisterGreeterHandler(greeterSvc.Server(), new(handler.Greeter))

	// Run service
	if err := greeterSvc.Run(); err != nil {
		log.Fatal(err)
	}
}
